<?php

class Application_Model_DbTable_ArticleCategory extends Zend_Db_Table_Abstract
{

    protected $_name = 'article_categories';

     protected $_dependentTables = array(
        "Application_Model_DbTable_Article",
        "Application_Model_DbTable_ArticleCategory"
    );
    
    protected $_referenceMap = array(
        "Parent" => array(
            'columns' => "parent_id",
            'refTableClass' => "Application_Model_DbTable_ArticleCategory",
            'refColumns'=>"idcategories"
        )
    );
    
    public function renderSelectParent($id=null, $parent=0){
        $rows = $this->fetchAll();
        if($id!=null){
            $rows = $this->fetchAll("idcategories != $id");
        }
        
        if($parent==0){
            $string = 
            "<select name='parent_id' id='parent-cat' class='parent-cat'>
                <option value='0' selected='selected'>---None---</option>";
        }else{
            $string = 
            "<select name='parent_id' id='parent-cat' class='parent-cat'>
                <option value='0'>---None---</option>";
        }
        foreach($rows as $row){
            $selected = ($parent==$row->idcategories)?"selected='selected'":"";
            $string.=
                "<option  $selected value='$row->idcategories'>---$row->category_name---</option>";
        }
        $string.="</select>";
        return $string;
    }
    
    
    public function buildListParent(){
        $rows = $this->fetchAll("parent_id IS NULL");
        $options[0] = "None";
        foreach($rows as $row){
            $options[$row->idcategories] = $row->category_name;
            $c_ops =  $this->renderList($row->idcategories);
            foreach($c_ops as $key=>$value){
                $options[$key] = $value;
            }
        }
        return $options;
    }
    
    private function renderList($id,$level=0){
        $p_row = $this->find($id)->current();
        $c_row = $this->fetchAll("parent_id=$id");
        if($c_row->count()<=0){
            return array();
        }
        $tab = "";
        for($i=0;$i<=$level;$i++){
            $tab.="•——";
        }
        foreach($c_row as $r){
            $ops[$r->idcategories] = $tab."•".$r->category_name;
            $c_ops =  $this->renderList($r->idcategories,$level+1);
            foreach($c_ops as $key=>$value){
                $ops[$key] = $value;
            }
        }
        return $ops;
    }
    
}
